<template>
  <div class="role-management">
    <!-- 搜索表单 -->
    <div class="search-form">
      <div class="form-row">
        <div class="form-item-inline">
          <label>角色名称</label>
          <el-input
            v-model="searchForm.roleName"
            placeholder="请输入角色名称"
            clearable
          />
        </div>
        <div class="form-item-inline">
          <label>状态</label>
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </div>
        <div class="button-group">
          <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh" class="reset-btn">重置</el-button>
        </div>
      </div>
    </div>

    <div style="margin-bottom: 20px;">
      <el-button type="success" @click="handleAdd" :icon="Plus" class="add-btn">新增角色</el-button>
    </div>

    <!-- 角色列表容器 -->
    <div class="role-list-container">
      <!-- 角色列表滚动容器 -->
      <div class="list-scroll-container">
        <!-- 表头 -->
        <div class="list-header">
          <div class="header-item name-col">角色名称</div>
           <div class="header-item code-col">角色编码</div>
<!--          <div class="header-item type-col">角色类型</div>-->
          <!-- <div class="header-item permissions-col">权限数量</div> -->
          <!-- <div class="header-item status-col">状态</div> -->
<!--          <div class="header-item date-col">创建时间</div>-->
          <div class="header-item action-col">操作</div>
        </div>

        <div class="list-content" v-if="paginatedData.length > 0">
          <div
            v-for="(role, index) in paginatedData"
            :key="role.id"
            class="list-item"
          >
            <div class="list-row">
              <div class="name-col">
                <div class="name-content">
                  <el-icon :size="20" color="#667eea">
                    <UserFilled />
                  </el-icon>
                  <span class="name">{{ role.description }}</span>
                </div>
              </div>
              <div class="code-col">
                <span>{{ role.name }}</span>
              </div>
<!--              <div class="type-col">-->
<!--                <el-tag :type="getTypeTagType(role.type)" size="small">-->
<!--                  {{ getTypeLabel(role.type) }}-->
<!--                </el-tag>-->
<!--              </div>-->
             <!--  <div class="permissions-col">
                <el-tag type="info" size="small">{{ role.permissions?.length || 0 }} 项</el-tag>
              </div>
              <div class="status-col">
                <el-tag :type="getStatusTagType(role.status)" size="small">
                  {{ role.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </div> -->
<!--              <div class="date-col">-->
<!--                <span>{{ role.createTime }}</span>-->
<!--              </div>-->
              <div class="action-col">
                <div class="action-buttons">
                  <el-button type="primary" size="small" plain @click="handleEdit(role)" style="color: #a685ff; border-color: #a685ff; background-color: #f3f0ff;">编辑</el-button>
                  <el-button type="info" size="small" plain @click="handlePermissions(role)">权限</el-button>
                  <!-- <el-button type="success" size="small" plain @click="handlePreviewMenus(role)">预览菜单</el-button> -->
                  <el-button type="danger" size="small" plain @click="handleDelete(role)">删除</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无角色数据" />
        </div>
      </div>
    </div>

    <!-- 分页 - 右下角固定 -->
    <div class="pagination-fixed">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
      />
    </div>

    <!-- 角色弹窗组件 -->
    <RoleDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      @submit="handleDialogSubmit"
      @cancel="resetForm"
    />

    <!-- 权限配置弹窗组件 -->
    <PermissionDialog
      v-model:visible="permissionDialogVisible"
      :role-info="currentRole || { id: 0, name: '', code: '' }"
      :permissions="currentRole?.permissions || []"
      @submit="handlePermissionSubmit"
      @cancel="handlePermissionCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, UserFilled } from '@element-plus/icons-vue'
import RoleDialog from './components/RoleDialog.vue'
import PermissionDialog from './components/PermissionDialog.vue'
import {
  addRole, deleteRole,
  getRoleList, getRolePermissions,
  type Role,
  updateRole
} from "@/api/sys/role.api.ts";


// 搜索表单
const searchForm = ref({
  roleName: '',
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)



// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<Role>>({})

// 权限配置弹窗相关
const permissionDialogVisible = ref(false)
const currentRole = ref<Role | null>(null)

// 模拟角色数据
const roleData = ref<Role[]>([])
getRoleList().then((res) => {
  roleData.value = res
})

// 过滤后的数据
const filteredData = computed(() => {
  return roleData.value.filter(role => {
    const nameMatch = !searchForm.value.roleName ||
      role.name.toLowerCase().includes(searchForm.value.roleName.toLowerCase())
    const statusMatch = !searchForm.value.status || role.status === searchForm.value.status

    return nameMatch && statusMatch
  })
})

// 分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 获取角色类型标签类型
const getTypeTagType = (type: string) => {
  return type === 'system' ? 'warning' : 'info'
}

// 获取角色类型标签文本
const getTypeLabel = (type: string) => {
  return type === 'system' ? '系统角色' : '自定义角色'
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  return status === 'active' ? 'success' : 'danger'
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.success('搜索完成')
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    roleName: '',
    status: ''
  }
  currentPage.value = 1
  ElMessage.info('已重置搜索条件')
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  formData.value = {
    name: '',
    description: '',
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (role: Role) => {
  dialogTitle.value = '编辑角色'
  formData.value = { ...role }
  dialogVisible.value = true
}

// 权限管理
const handlePermissions = (role: Role) => {
  getRolePermissions(role.id).then((res) => {
    currentRole.value = res
    permissionDialogVisible.value = true
  }).catch((err) => {
    console.error(err)
  })
}

// 切换状态
// const handleToggleStatus = (role: Role) => {
//   const newStatus = role.status === 'active' ? 'inactive' : 'active'
//   const action = newStatus === 'active' ? '启用' : '禁用'
//
//   ElMessageBox.confirm(
//     `确定要${action}角色"${role.name}"吗？`,
//     '确认操作',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     }
//   ).then(() => {
//     role.status = newStatus
//     ElMessage.success(`角色"${role.name}"已${action}`)
//   }).catch(() => {
//     ElMessage.info('操作已取消')
//   })
// }

// 删除角色
const handleDelete = (role: Role) => {
  // if (role.type === 'system') {
  //   ElMessage.warning('系统角色不能删除')
  //   return
  // }

  ElMessageBox.confirm(
    `确定要删除角色"${role.name}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = roleData.value.findIndex(r => r.id === role.id)
    if (index > -1) {
      deleteRole(role.id).then(() => {
        roleData.value.splice(index, 1)
        ElMessage.success('角色已删除')
      })
    }
  }).catch(() => {
    ElMessage.info('操作已取消')
  })
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 弹窗提交
const handleDialogSubmit = (data: Role) => {
  if (data.id) {
    console.log(data)
    updateRole(data).then((res) => {
      console.log(res)
      ElMessage.success('角色信息已更新')
    })
    // 编辑
    const index = roleData.value.findIndex(r => r.id === data.id)
    if (index > -1) {
      roleData.value[index] = { ...roleData.value[index], ...data }
      ElMessage.success('角色信息已更新')
    }
  } else {
    // 新增
    const newRole: Role = {
      name: data.name!,
      description: data.description!,
    }
    // TODO 接口增加角色
    addRole(newRole).then((res) => {
      newRole.id = res.id
      roleData.value.unshift(newRole)
      ElMessage.success('角色已添加')
    })
  }

  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.value = {}
}

// 权限配置提交
const handlePermissionSubmit = (role: Role) => {
  if (currentRole.value) {
    const index = roleData.value.findIndex(r => r.id === currentRole.value!.id)
    if (index > -1) {
      roleData.value[index].permissions = role.permissions
      ElMessage.success(`角色"${currentRole.value.name}"的权限已更新`)
    }
  }
  permissionDialogVisible.value = false
  currentRole.value = null
}

// 权限配置取消
const handlePermissionCancel = () => {
  permissionDialogVisible.value = false
  currentRole.value = null
}



// 根据角色权限过滤菜单的工具函数
const filterMenusByPermissions = (permissions: string[]) => {
  const backendMenus = [
    {
      key: 'dashboard',
      label: '首页',
      path: '/',
      iconKey: 'dashboard'
    },
    {
      key: 'user-permission',
      label: '角色管理',
      path: '/user-permission',
      iconKey: 'roleManagement'
    },
    {
      key: 'chat',
      label: '智库问答',
      path: '/chat',
      iconKey: 'chat'
    },
    {
      key: 'knowledge-plus',
      label: '智库+',
      path: '/knowledge-plus',
      iconKey: 'knowledgePlus',
      children: [
        {
          key: 'chart-query',
          label: '图表查询',
          path: '/knowledge-plus/chart-query',
          iconKey: 'chartQuery'
        },
        {
          key: 'result-matching',
          label: '成果匹配',
          path: '/knowledge-plus/result-matching',
          iconKey: 'resultMatching'
        },
        {
          key: 'translation-assistant',
          label: '翻译助手',
          path: '/knowledge-plus/translation-assistant',
          iconKey: 'translationAssistant'
        },
        {
          key: 'ocr-recognition',
          label: '图文识别',
          path: '/knowledge-plus/ocr-recognition',
          iconKey: 'ocrRecognition'
        },
        {
          key: 'doc-assistant',
          label: '文档助手',
          path: '/knowledge-plus/doc-assistant',
          iconKey: 'docAssistant'
        },
        {
          key: 'solution-assistant',
          label: '标书助手',
          path: '/knowledge-plus/solution-assistant',
          iconKey: 'solutionAssistant'
        }
      ]
    },
    {
      key: 'knowledge-graph',
      label: '知识图谱',
      path: '/knowledge-plus/knowledge-graph',
      iconKey: 'knowledgeGraph'
    },
    {
      key: 'personal-knowledge',
      label: '个人知识库',
      path: '/personal-knowledge',
      iconKey: 'personalKnowledge'
    },
    {
      key: 'recent-chats-parent',
      label: '近期对话',
      iconKey: 'recentChats',
      children: [
        {
          key: 'pipeline-construction',
          label: '管道施工',
          path: '/chat?topic=pipeline-construction'
        },
        {
          key: 'pipeline-maintenance',
          label: '管道维修',
          path: '/chat?topic=pipeline-maintenance'
        },
        {
          key: 'welding-construction',
          label: '焊接施工注意',
          path: '/chat?topic=welding-construction'
        },
        {
          key: 'recent-chats',
          label: '查看更多',
          path: '/recent-chats'
        }
      ]
    }
  ]

  // 递归过滤菜单
  const filterMenus = (menus: any[]) => {
    return menus.filter(menu => {
      // 检查当前菜单是否有权限
      const hasPermission = permissions.includes(menu.key)

      if (!hasPermission) {
        return false
      }

      // 如果有子菜单，递归过滤子菜单
      if (menu.children) {
        menu.children = filterMenus(menu.children)
        // 如果过滤后没有子菜单，但父菜单有权限，仍然保留父菜单
      }

      return true
    })
  }

  return filterMenus(backendMenus)
}

// 获取角色可访问的菜单
const getRoleMenus = (roleId: number) => {
  const role = roleData.value.find(r => r.id === roleId)
  if (!role || !role.permissions) {
    return []
  }

  return filterMenusByPermissions(role.permissions)
}

// 预览角色菜单
/* const handlePreviewMenus = (role: Role) => {
  const menus = getRoleMenus(role.id)

  if (menus.length === 0) {
    ElMessage.warning(`角色"${role.name}"暂无菜单权限`)
    return
  }

  // 格式化菜单结构用于显示
  const formatMenus = (menuList: any[], level = 0): string[] => {
    const results: string[] = []
    menuList.forEach(menu => {
      const indent = '　'.repeat(level)
      results.push(`${indent}• ${menu.label}`)
      if (menu.children && menu.children.length > 0) {
        results.push(...formatMenus(menu.children, level + 1))
      }
    })
    return results
  }

  const menuText = formatMenus(menus).join('\n')

  ElMessageBox.alert(
    menuText,
    `角色"${role.name}"可访问的菜单`,
    {
      confirmButtonText: '确定',
      type: 'info',
      customStyle: {
        width: '500px'
      }
    }
  )
} */

onMounted(() => {
  // 组件挂载时的初始化逻辑
})
</script>

<style scoped>
.role-management {
  padding: 24px;
}

/* 搜索表单样式 - 美化版本 */
.search-form {
  padding: 0 24px 20px 0px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.form-item-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.form-item-inline label {
  font-size: 14px;
  font-weight: 600;
  color: #475569;
  white-space: nowrap;
  min-width: 60px;
}

.form-item-inline .el-input,
.form-item-inline .el-select {
  width: 160px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

.add-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 角色列表容器样式 */
.role-list-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  overflow: hidden;
  max-height: 550px;
  display: flex;
  flex-direction: column;
}

/* 列表头部样式 */
.list-header {
  display: flex;
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
  border-bottom: 1px solid #c7d2fe;
  padding: 16px 20px;
  font-weight: 600;
  color: #4338ca;
  font-size: 16px;
  position: sticky;
  top: 0;
  z-index: 10;
  min-width: max-content;
}

.header-item {
  display: flex;
  align-items: center;
}

.name-col {
  flex: 1.2;
  min-width: 150px;
}

.code-col {
  flex: 1;
  min-width: 120px;
}

.type-col {
  flex: 1;
  min-width: 100px;
}

.permissions-col {
  flex: 1;
  min-width: 100px;
}

.status-col {
  flex: 0.8;
  min-width: 80px;
}

.date-col {
  flex: 1.2;
  min-width: 160px;
}

.action-col {
  flex: 2;
  min-width: 240px;
}

/* 列表滚动容器 */
.list-scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: auto;
}

.list-content {
  background: white;
}

.list-item {
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.list-item:hover {
  background: #f8fafc;
}

.list-item:last-child {
  border-bottom: none;
}

.list-row {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  min-height: 60px;
  min-width: max-content;
}

/* 角色名称列样式 */
.name-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.name {
  font-weight: 500;
  color: #1f2937;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 6px;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
}

/* 分页样式 - 右下角固定 */
.pagination-fixed {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 100;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
}

.pagination-fixed :deep(.el-pagination) {
  margin: 0;
}

.pagination-fixed :deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .el-pager li:hover) {
  background: #f3f4f6;
}

.pagination-fixed :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.pagination-fixed :deep(.el-pagination .btn-prev),
.pagination-fixed :deep(.el-pagination .btn-next) {
  border-radius: 6px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .btn-prev:hover),
.pagination-fixed :deep(.el-pagination .btn-next:hover) {
  background: #f3f4f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-management {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .form-item-inline {
    min-width: auto;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .form-item-inline label {
    min-width: auto;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0;
    flex-direction: column;
    gap: 8px;
  }

  .search-btn,
  .reset-btn,
  .add-btn {
    width: 100%;
  }

  .list-header,
  .list-row {
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .pagination-fixed {
    position: relative;
    bottom: auto;
    right: auto;
    margin-top: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}

@media (max-width: 1024px) {
  .form-row {
    gap: 16px;
  }

  .form-item-inline {
    min-width: 180px;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 140px;
  }

  .button-group {
    flex-wrap: wrap;
  }
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}
</style>